package com.ricky.chat.server.handler;

import com.ricky.chat.common.dto.JsonMsgDto;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroupException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Set;
import static com.ricky.chat.server.sevice.RickyServer.channels;
import static com.ricky.chat.server.sevice.RickyServer.userChannelMap;

/**
 * 假设你有一个自定义的 Handler 来处理业务逻辑
 */
public class ServerHandler extends SimpleChannelInboundHandler<JsonMsgDto> {
    private final static Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 客户端连上来了，将它的 Channel 加入到全局 Group 中
        channels.add(ctx.channel());
        LOGGER.info("客户端已连接: {}", ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JsonMsgDto msg) {
        // ... 处理接收到的消息 ...
        LOGGER.info("用户是{},收到来自 {} 的消息: {}", msg.getUserName(),ctx.channel().remoteAddress(), msg.getContent());

        if(!userChannelMap.containsKey(msg.getUserName())) {
            userChannelMap.put(msg.getUserName(), ctx.channel());
            LOGGER.info("用户 {} 注册成功，关联到 Channel: {}", msg.getUserName(), ctx.channel().remoteAddress());
        }else{
            LOGGER.info("用户 {} 已经注册，Channel: {}", msg.getUserName(), ctx.channel().remoteAddress());
        }

        Set<String> strings = userChannelMap.keySet();
        for (String string : strings) {
            LOGGER.info("userChannelMap里面的数据 {} ", string);
        }

        // 示例：将收到的消息广播给所有客户端
        JsonMsgDto broadcastMsg = new JsonMsgDto();
        //broadcastMsg.setContent("广播: " + msg.getContent());
        broadcastMsg.setContent(msg.getContent());
        broadcastMsg.setUserName(msg.getUserName());

        LOGGER.info("准备广播消息给 {} 个客户端", channels.size());

        // 添加更完善的错误处理
        channels.writeAndFlush(broadcastMsg).addListener(future -> {
            if (future.isSuccess()) {
                LOGGER.info("广播消息发送成功");
            } else {
                if (future.cause() instanceof io.netty.channel.group.ChannelGroupException) {
                    ChannelGroupException groupException = (ChannelGroupException) future.cause();
                    for (Map.Entry<Channel, Throwable> entry : groupException) {
                        LOGGER.error("向 Channel {} 发送消息失败: {}",
                                entry.getKey().remoteAddress(),
                                entry.getValue().getMessage());
                    }
                } else {
                    LOGGER.error("广播消息发送失败", future.cause());
                }
            }
        });
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 客户端断开了，Channel 会自动从 ChannelGroup 中移除
        LOGGER.info("客户端已断开: {}", ctx.channel().remoteAddress());
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // ... 异常处理 ...
        ctx.close();
    }
}

